package com.example.tests;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.apache.commons.lang3.RandomStringUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;

import com.example.fw.ApplicationManager;

import static com.example.tests.GroupDataGenerator.generateRandomGroups;
import static com.example.tests.GroupDataGenerator.loadGroupsFromXmlFile;
import static com.example.tests.GroupDataGenerator.loadGroupsFromCsvFile;
import static com.example.tests.ContactDataGenerator.generateRandomContacts;
import static com.example.tests.ContactDataGenerator.loadContactsFromXmlFile;
import static com.example.tests.ContactDataGenerator.loadContactsFromCsvFile;

public class TestBase {
	
	protected static ApplicationManager app;
	private int checkCounter;
	private int checkFrequency;

	@BeforeTest
	public void setUp() throws Exception {
		String configFile = System.getProperty("configFile", "application.properties");
		Properties properties = new Properties();
		properties.load(new FileReader(configFile));
		app = new ApplicationManager(properties);
		checkCounter = 0;
		checkFrequency = Integer.parseInt(properties.getProperty("check.frequency", "0"));
	}

	protected boolean wantToCheck() {
		checkCounter++;
		if (checkCounter > checkFrequency) {
			checkCounter = 0;
			return true;
		} else {
			return false;
		}
	}
	
	@AfterTest
	public void tearDown() throws Exception {
		app.stop();
	}
	
	@DataProvider
	public Iterator<Object[]> randomValidGroupGenerator() {
		return wrapGroupForDataProvider(generateRandomGroups(5)).iterator();
	}
	
	@DataProvider
	public Iterator<Object[]> groupsFromXmlFile() throws IOException {
		 return wrapGroupForDataProvider(loadGroupsFromXmlFile(new File("groups.xml"))).iterator();
	}
	 
	@DataProvider
	public Iterator<Object[]> groupsFromCsvFile() throws IOException {
		 return wrapGroupForDataProvider(loadGroupsFromCsvFile(new File("groups.txt"))).iterator();
	}
	
	public static List<Object[]> wrapGroupForDataProvider(List<GroupData> groups) {
		List<Object[]> list = new ArrayList<Object[]>();
		for (GroupData group : groups) {
			list.add(new Object[]{group});
		}
		return list;
	}

	@DataProvider
	public Iterator<Object[]> randomValidContactGenerator() {
		return wrapContactForDataProvider(generateRandomContacts(5)).iterator();
	}
	
	@DataProvider
	public Iterator<Object[]> contactsFromXmlFile() throws IOException {
		return wrapContactForDataProvider(loadContactsFromXmlFile(new File("contacts.xml"))).iterator();
	}
	
	@DataProvider
	public Iterator<Object[]> contactsFromCsvFile() throws IOException {
		return wrapContactForDataProvider(loadContactsFromCsvFile(new File("contacts.txt"))).iterator();
	}

	public static List<Object[]> wrapContactForDataProvider(List<ContactData> contacts) {
		List<Object[]> list = new ArrayList<Object[]>();
		for (ContactData contact : contacts) {
			list.add(new Object[]{contact});
		}
		return list;
	}
	  
    public static String generateRandomString(int textLength) {
    	Random rnd = new Random();
		if (rnd.nextInt(10) == 0) {
			return "";
			} else {
				return RandomStringUtils.random(textLength, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz");
			}
	}
      
    public static String generateTextSymbols(int textLength) {
	    StringBuilder textLatinSymbols = new StringBuilder("Z");
	    Random rnd = new Random();
	    while (textLatinSymbols.length() < textLength) {
	        int stringLength = rnd.nextInt(20);
	        if (stringLength > 0) {
	        	textLatinSymbols.append(" ").append(RandomStringUtils.random(stringLength,
	                      "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"));
	        	}
	        }
	    if (textLatinSymbols.length() > textLength) {
	    	textLatinSymbols.delete(textLength, textLatinSymbols.length());
	    	}
	    return textLatinSymbols.toString();
	}
	  
	public static String generateRandomStringWithNumbers(int stringLength) {
		Random rnd = new Random();
		if (rnd.nextInt(10) == 0) {
			return "";
			} else {
				return RandomStringUtils.randomNumeric(stringLength);
			}
	}

	public static String[] generateRandomDate() {
		Random rnd = new Random();
		String[] date = {"-", "-", ""};
		if (rnd.nextInt(10) != 0) {
			GregorianCalendar gc = new GregorianCalendar();
			int year = randBetween(1900, 2013);
			int dayOfYear = randBetween(1, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
			gc.set(Calendar.YEAR, year);
			gc.set(Calendar.DAY_OF_YEAR, dayOfYear);
			String[] months = {"January", "February", "March", "April", "May", "June", "July", 
					  "August", "September", "October", "November", "December"};
			date[0] = Integer.toString(gc.get(Calendar.DAY_OF_MONTH));
			date[1] = months[gc.get(Calendar.MONTH)];
			date[2] = Integer.toString(gc.get(Calendar.YEAR));
			}
		return date;
	}

	public static int randBetween(int start, int end) {
		return start + (int)Math.round(Math.random() * (end - start));
	}
}
